package com.aline.seo.configuration;

import com.aline.seo.entity.Menu;
import com.aline.seo.mapper.RoleMapper;
import com.aline.seo.repository.MenuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName CustomerFilterInvocationSecurityMetadataSource
 * @Description
 * @Author 孟志浩
 * @Date 2019/4/11 11:41
 **/
@Component
public class CustomerFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private MenuRepository menuRepository;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        HttpServletRequest req = ((FilterInvocation)o).getRequest();
        String method = req.getMethod();
        String reqUrl = ((FilterInvocation)o).getRequestUrl();
        List<Menu> menus = menuRepository.findMenusByMethod(method.toUpperCase());
        List<Menu> accountMenu = menus.stream().filter(menu -> antPathMatcher.match(menu.getUrl(), reqUrl))
                .collect(Collectors.toList());
        // 如果没有配置默认登录就可以访问
        if(accountMenu.size() == 0){
            return SecurityConfig.createList("ROLE_LOGIN");
        }
        // 只匹配第一个需要的角色，配置角色时url不能重复
        List<String> roles = roleMapper.getRoleNamesByMenuId(accountMenu.get(0).getId());
        String[] rs = new String[roles.size()];
        String[] accessRole = roles.toArray(rs);
        return SecurityConfig.createList(accessRole);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }

}
